package com.woniuxy.automotivemanagementsystem.controller;

import com.woniuxy.automotivemanagementsystem.entity.Menu;
import com.woniuxy.automotivemanagementsystem.entity.Role;
import com.woniuxy.automotivemanagementsystem.entity.User;
import com.woniuxy.automotivemanagementsystem.service.MenuService;
import com.woniuxy.automotivemanagementsystem.service.RoleService;
import com.woniuxy.automotivemanagementsystem.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@CrossOrigin
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    /*
    * userinfoview.vue中的查询所有角色方法，用于分配角色时显示所有能分配的角色
    * */
    @GetMapping("/findAll")
    public Result findAll(){
        List<Role> list = roleService.list();
        list.forEach(role -> {
            role.setMenus(menuService.queryMenuByRid(role.getRid()));
        });
        return Result.success(list);
    }
    /*
    * RoleView.vue中的修改或新增角色接口
    * */
    @PutMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Role role){
        roleService.saveOrUpdate( role);
        return Result.success(true);
    }
    /*
    * RoleView.vue中的删除角色接口
    * */
    @DeleteMapping("/delectIfNotExistsUser/{rid}")
    public Result delectIfNotExistsUser(@PathVariable("rid") Integer rid){
        if(rid ==  null){
            return Result.error("角色为空");
        }
        List<User> list = roleService.selectUserByRid(rid);
        if(!list.isEmpty()){
            return Result.error("该角色下有用户，不能删除");
        }
        roleService.removeById( rid);
        return Result.success(true);
    }
    /*
    * 重新分配角色菜单接口
    * */
    @PutMapping("/updateMenusByRoleId/{rid}")
    public Result updateMenusByRoleId(@PathVariable("rid") Integer rid,@RequestBody List<Menu> menus){
        if(rid == null || rid == 0){
            return Result.error("角色为空");
        }
        roleService.updateMenusByRoleId(rid,menus);
        return Result.success(true);
    }
}
